var $= require('../../../lib/jquery');
require('./date');
var util = {};
util.getHash = function (name) {
  var params = location.hash.substring(1).split('&');

  for (var i = 0; i < params.length; i++) {
    var tmp = params[i].split("=");

    if (tmp.length > 1 && name == tmp[0]) {
      return tmp[1];
    }
  }
  return null;
};
/**
 * 获取对象长度
 * @param  {Object} o 当前对象
 * @return {Number}   返回长度
 */
util.getProLen = function (o) {
  var len = 0;

  if (o && typeof o === 'object') {
    for (var i in o) {
      if (o.hasOwnProperty(i)) {
        len++;
      }
    }

  }

  return len;
};
util.setSearch = function (opt) {
  if (!this.getProLen(opt)) {
    return;
  }

  var search = location.search;

  for (var name in opt) {
    search = this.updateQuery(search, name, opt[name]);
  }

  search = search.replace(/(.+)&$/g, '$1');

  History.replaceState(this.getActiveId(), document.title, location.pathname + search);
};
util.getParam = function (param, str) {
  var r,
    reg;
  reg = new RegExp("[?|&]" + param + "=(.*?)(&|#|$)", "i");
  r = str ? ("?" + str).match(reg) : window.location.search.match(reg);
  return r && decodeURIComponent(r[1]) || undefined;
};
util.clone = function (obj) {
  var newObj = null;

  if (!obj) {
    newObj = obj;
  } else if (typeof obj != 'object') {
    newObj = obj;
  } else {
    newObj = obj.constructor == Array ? [] : {};

    for (var i in obj) {
      newObj[i] = util.clone(obj[i]);
    }
  }
  return newObj;
};
util.parseUrl = function (urlStr, noDecode) {
  var url = urlStr || window.location.href;
  var a = document.createElement('a');
  a.href = url;
  return {
    source: url,
    protocol: a.protocol.replace(':', ''),
    host: a.hostname,
    port: a.port,
    query: a.search,
    params: (function () {
      var ret = {},
        seg = a.search.replace(/^\?/, '').split('&'),
        len = seg.length,
        i = 0,
        s;
      for (; i < len; i++) {
        if (!seg[i]) {
          continue;
        }
        s = seg[i].split('=');
        ret[s[0]] = !noDecode ? decodeURIComponent(s[1]) : s[1];
      }
      return ret;

    })(),
    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
    hash: a.hash.replace('#', ''),
    path: a.pathname.replace(/^([^\/])/, '/$1'),
    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
    segments: a.pathname.replace(/^\//, '').split('/')
  };
};
util.setCookie = function (name, value, ms) {
  var expires = "";
  if (ms) {
    var date = new Date();
    date.setTime(date.getTime() + ms);
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + value + expires + "; path=/;";
};
 util.getCookie = function (name) {
   var arr,
     reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
   if (arr = document.cookie.match(reg)) {
     return decodeURIComponent(arr[2]);
   } else {
     return '';
   }
 };
 
util.fetch = function (url, data, options) {
  var domainReg = /(https?:)?\/\/[^\.]*\.([^\/|?]*)/g;
  var def = $.Deferred();
  
  var defaults = {
    type: "GET",
    dataType: 'json',
    jsonpCallback: "",
    timeout: 0, //默认超时时长
    // apiPrefix:'http://117.121.38.74:8089/',
    apiPrefix:'https://app.jkxch.bjxch.gov.cn/',
    beforeSend: function () {},
    complete: function () {},
    cache: true,
    processData:true
  };
  
  var token = sessionStorage.getItem('token') || 'null';
  var opts = $.extend(defaults, options);
  var ajaxObj = {
    url: domainReg.test(url) ? url : opts.apiPrefix + url,
    data: $.extend({}, data, {
      token:token,
    }),
    timeout: opts.timeout,
    dataType: opts.dataType,
    type: opts.type,
    jsonpCallback: opts.jsonpCallback,
    beforeSend: opts.beforeSend,
    complete: opts.complete,
    processData: opts.processData,
    cache:opts.cache,
    success: function (data, status, xhr) {
      if (data && data.msg && data.msg.toString().toLocaleLowerCase() == 'success' || data.code == "USR000") {
        return def.resolve(data, status, xhr);
      }
      else if(data.code=='USR124'){
        sessionStorage.clear();
         location.href='./login.html'
      }
      else{  
        return def.reject(data, status, xhr);
      }
    },
    error: function (data, errorType, error) {
      return def.reject(data, errorType, error);
    }
  };
  if (opts.contentType) {
    ajaxObj.contentType = opts.contentType;
  }
  $.ajax(ajaxObj)
  return def.promise()
};
util.redirect  = function () {
  var token = sessionStorage.getItem('token')
  var login = location.href.indexOf('login') > -1;
  var find = location.href.indexOf('find') > -1;
  var registe = location.href.indexOf('registe') > -1;
  if (!token && (!login && !find && !registe) && location.pathname != '') {
    location.replace('./login.html')
  }
}
var t = window.onload;
window.onload =  function () {

  util.redirect()
  t && t();
}

module.exports = util;